# -*- coding: utf-8 -*-
from odoo import fields, models
from odoo.exceptions import UserError


class WizardUpdateVoucherName(models.Model):
    _name = 'wizard.update.voucher.name'
    _description = '凭证断号处理'

    period_id = fields.Many2one('account.period', string='期别')
    voucher_category_id = fields.Many2one('account.voucher.category', string='凭证类型')

    def update_voucher_name(self):
        """月末凭证断号处理"""
        # ir_sequence_list = self.env['ir.sequence'].search([('code', 'like', 'account.voucher')])
        year = self.period_id.date_start.year
        month = '%02d' % self.period_id.date_start.month
        ir_sequence = self.voucher_category_id.ir_seq_id
        try:
            code_result = ir_sequence.prefix % ({'year': year, 'month': month})  # 规则编号
        except Exception as e:
            raise UserError('凭证编号规则不正确，请联系管理人员。正确规则示例：FG%{year}s%{month}s')
        d_num = '%0{}d'.format(ir_sequence.padding)
        self._cr.execute("""
               select id,name from account_voucher where name like '{code_result}%' and state !='cancel' order by name
               """.format(code_result=code_result))
        # all_list = self._cr.dictfetchall()
        all_list = self.env['account.voucher'].search([('name', 'like', code_result), ('state', 'not in', ['cancel'])])
        # 查询所有编号
        voucher_name_second_list = [voucher.name[-ir_sequence.padding:] for voucher in all_list]
        # voucher_list = self.browse([voucher.id for voucher in all_list])
        voucher_list = all_list
        voucher_number = len(all_list)
        # if voucher_name_second_list and int(voucher_name_second_list[-1]) > voucher_number:
        if voucher_name_second_list:
            has_change = []  # 已处理的凭证
            voucher_len = voucher_number  # 总凭证数
            i = j = 0  # i 编号 j列表序号
            while voucher_len > 0:
                if voucher_list[j].id not in has_change:
                    voucher_list[j].name = "%s%s" % (code_result, d_num % (i + 1))
                    i += 1
                    voucher_len -= 1
                    has_change.append(voucher_list[j].id)
                    # 判断是否有关联凭证
                    if voucher_list[j].child_ids:
                        for child in voucher_list[i].child_ids:
                            child.name = "%s%s" % (code_result, d_num % (i + 1))
                            i += 1
                            voucher_len -= 1
                            has_change.append(child.id)
                j += 1

    def check_voucher_name(self):
        """检测断号"""

        # ir_sequence_list = self.env['ir.sequence'].search([('code', 'like', 'account.voucher')])
        year = self.period_id.date_start.year
        month = '%02d' % self.period_id.date_start.month
        break_number_vals_list = []  # 断号
        ir_sequence = self.voucher_category_id.ir_seq_id
        # for ir_sequence in ir_sequence_list:
        try:
            code_result = ir_sequence.prefix % ({'year': year, 'month': month})  # 规则编号
        except Exception as e:
            raise UserError('凭证编号规则不正确，请联系管理人员。正确规则示例：FG%{year}s%{month}s')
        d_num = '%0{}d'.format(ir_sequence.padding)
        self._cr.execute("""
                      select id,name from account_voucher where name like '{code_result}%' and state !='cancel' order by name
                      """.format(code_result=code_result))
        all_list = self._cr.dictfetchall()
        voucher_name_second_list = [voucher.get('name')[-ir_sequence.padding:] for voucher in all_list]
        real_number = [d_num % (i + 1) for i in range(len(all_list))]  # 正常序列编号
        break_number_list = set(real_number) - set(voucher_name_second_list)  # 断号
        break_name_list = ["%s%s" % (code_result, break_number) for break_number in break_number_list]  # 断号的凭证编号
        error_number_list = set(voucher_name_second_list) - set(real_number)  # 异常号码
        error_name_list = ["%s%s" % (code_result, error_number) for error_number in error_number_list]  # 异常的凭证编号
        if break_name_list or error_name_list:
            message_break = '断号编号：%s' % (','.join(break_name_list))
            message_error = '异常编号：%s' % (','.join(error_name_list))
            raise UserError('%s \n %s' % (message_break, message_error))
        else:
            raise UserError('恭喜！没有错误号码')
